<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/11/16
 * Time: 10:58
 */
namespace app\common\library\wxpay;

use app\common\model\Config;
use EasyWeChat\Factory;
use think\Exception;

class WechatPay
{

    public static function createOrder($title, $orderSn, $totalFee, $openid = ''){
        $config = [
            // 必要配置
            'app_id'             => Config::getConfigValue('miniapp_wechat_appid'),
            'mch_id'             => Config::getConfigValue('payment_wechat_mchid'), // 商户号
            'key'                => Config::getConfigValue('payment_wechat_mchsecret'), // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '', // XXX: 绝对路径！！！！
            'key_path'           => '',      // XXX: 绝对路径！！！！
            'notify_url'         => getRealImg(Config::getConfigValue('wechat_pay_notify')),     // 你也可以在下单时单独设置来想覆盖它
        ];
        $app = Factory::payment($config);
        $payOptions  = [
            'openid' => $openid, // JSAPI 支付必填
            'body' => $title,
            'out_trade_no' => $orderSn,
            'total_fee' => $totalFee * 100,
            'trade_type' => 'JSAPI',
        ];

        $result = $app->order->unify($payOptions);
        //\think\Log::record('#result#' . json_encode($result));

        // 获取JSSDK的支付配置
        $payment = Factory::payment($config);
        $json = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
        //\think\Log::record('返回的数据：');
        //\think\Log::record($result);
        //\think\Log::record($json);

        return [
            'order_data' => $json,
            'order_sn' => $orderSn
        ];
    }
}